package com.fognl.core.net.handler.request;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import com.fognl.core.net.handler.AbstractRequest;
import com.fognl.core.net.handler.Request;
import com.fognl.core.net.handler.WorkerException;

/** Read a file, put its contents in a byte[]. Useless except for POC */
public class SimpleFileReadRequest extends AbstractRequest
{
	private File file;
	
	public SimpleFileReadRequest(File file)
	{
		super();
		this.file = file;
	}
	
	public File getFile() { return file; }
	
	public String toString()
	{
		return file.getAbsolutePath();
	}
	
	public Worker getWorker()
	{
		return new Request.Worker() {
			private byte[] fileBytes;

			public Object getData()
			{
				return fileBytes;
			}
			
			public void work(Request.Worker.Listener listener) throws WorkerException
			{
				try {
					InputStream in = new BufferedInputStream(new FileInputStream(file));
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					
					try {
						byte[] buf = new byte[4096];
						for(int read = in.read(buf); read != -1; read = in.read(buf))
						{
							Thread.yield();
							if(!listener.okToContinue(this))
								break;
							
							bos.write(buf, 0, read);
						}
						
						fileBytes = bos.toByteArray();
					}
					finally {
						try {
							bos.flush();
						} catch(Exception ex) {}
						
						try {
							bos.close();
						} catch(Exception ex) {}
						
						try {
							in.close();
						} catch(Exception ex) {}
					}
				}
				catch(Exception ex)
				{
					throw new WorkerException(ex.getMessage(), ex);
				}
			}
		};
	}
}
